<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <s-table
        ref="table"
        size="default"
        :rowKey="(record, index) => index"
        :columns="columns"
        :data="loadData"
        :scroll="{ x: true }"
        :pagination="{ showTotal: (total) => `共 ${total} 条` }"
        :showPagination="false"
      >
        <span slot="index" slot-scope="text, record, index">{{ index + 1 }} </span>
        <ellipsis slot="ellipsis" slot-scope="text">{{ text || '/' }}</ellipsis>
        <span slot="empty" slot-scope="text">{{ text || '/' }}</span>
        <span slot="time" slot-scope="text">{{ text | moment }}</span>
      </s-table>
    </a-card>
  </page-header-wrapper>
</template>

<script>
import { STable, Ellipsis } from '@/components'
import { getStatementList } from '@/api/statementAndStatistics'
import BigNumber from 'bignumber.js'
export default {
  components: {
    STable,
    Ellipsis
  },
  data () {
    return {
      queryParam: {
        Mode: 'CityRfyCategory',
        UserID: this.$store.getters.userid,
        strContent: {}
      },
      columns: [
        {
          title: '实物保障（户）',
          align: 'center',
          children: [{ title: '', align: 'center', dataIndex: 'name' }]
        },
        { title: '租赁补贴（户）', align: 'center', children: [] }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        parameter.pageSize = 100
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        return getStatementList(requestParameters).then((res) => {
          const { data, count } = res
          // 是否为数字
          function isNumber (val) {
            var reg = /^[+-]?\d*(\.\d*)?(e[+-]?\d+)?$/
            return reg.test(val)
          }
          // 列转行
          const columnsToLline = (data) => {
            const result = {}
            for (let index = 0; index < data.length; index++) {
              const element = data[index]
              let number = new BigNumber(0)
              for (const key in element) {
                const kv = result[key]
                if (kv) {
                  kv.push(element[key])
                } else {
                  result[key] = []
                  result[key].push(element[key])
                }
                if (isNumber(element[key])) {
                  number = number.plus(element[key])
                }
              }
              if (result.LJSS) {
                result.LJSS.push(number.toNumber())
              } else {
                result.LJSS = [number.toNumber()]
              }
              if (result.JZBZ) {
                result.JZBZ.push(new BigNumber(element.BNZR).minus(element.BNTC).toNumber())
              } else {
                result.JZBZ = [new BigNumber(element.BNZR).minus(element.BNTC).toNumber()]
              }
            }
            return result
          }
          // 转换为行数据
          const lineData = columnsToLline(data)
          const keysArr = Object.keys(lineData)
          const nameArr = [
            '正在实施保障',
            '正在轮候',
            '本年：进入保障',
            '本年：退出保障',
            '累计实施保障',
            `${new Date().getFullYear()}年度净增保障`
          ]
          const minusLength = keysArr.length - nameArr.length
          if (minusLength > 0) {
            // 补位
            nameArr.unshift(...new Array(minusLength))
          }
          // 渲染的行数据
          const $data = []
          for (const key in lineData) {
            const keyIndex = keysArr.findIndex((e) => e === key)
            const obj = {}
            const value = lineData[key]
            for (let index = 0; index < count; index++) {
              const newKey = lineData['BZLB'][index] + lineData['BZLX'][index]
              obj[newKey] = value[index]
            }
            if (!['BZLB', 'BZLX'].includes(key)) {
              obj.name = keyIndex ? nameArr[keyIndex] : ''
              $data.push(obj)
            }
          }
          for (let index = 0; index < count; index++) {
            const newKey = lineData['BZLB'][index] + lineData['BZLX'][index]
            if (lineData['BZLB'][index] === '租赁补贴') {
              this.columns[1].children.push({
                title: lineData['BZLX'][index],
                align: 'center',
                dataIndex: newKey
              })
            }
            if (lineData['BZLB'][index] === '实物') {
              this.columns[0].children.push({
                title: lineData['BZLX'][index],
                align: 'center',
                dataIndex: newKey
              })
            }
          }
          return {
            data: $data,
            count: Object.keys(lineData).length
          }
        })
      }
    }
  },
  methods: {
    tableRefresh (refresh = false) {
      this.$refs.table.refresh(refresh)
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .ant-table {
  td,
  tr {
    white-space: nowrap;
  }
}
</style>
